package com.kymatrix.kycarbon.xsmd.common.druid.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import javax.servlet.Filter;
import javax.servlet.Servlet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DruidConfig {
    
    @Value("${spring.datasource.druid.stat-view-servlet.url-pattern}")
    private String statViewServletUrlPatter;
    @Value("${spring.datasource.druid.stat-view-servlet.allow}")
    private String statViewServletAllow;
    @Value("${spring.datasource.druid.stat-view-servlet.deny}")
    private String statViewServletDeny;
    @Value("${spring.datasource.druid.stat-view-servlet.login-username}")
    private String statViewServletLoginUsername;
    @Value("${spring.datasource.druid.stat-view-servlet.login-password}")
    private String statViewServletLoginPassword;
    
    
    
    /**
     * 配置Druid 监控启动页面
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true")
    public ServletRegistrationBean<Servlet> druidStartViewServlet() {
        ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<>(
                new StatViewServlet(), statViewServletUrlPatter);
        servletRegistrationBean.addInitParameter("allow", statViewServletAllow);
        // 黑名单
        servletRegistrationBean.addInitParameter("deny", statViewServletDeny);
        // 登录查看信息的账密，用于登录Druid监控后台
        servletRegistrationBean.addInitParameter("loginUsername", statViewServletLoginUsername);
        servletRegistrationBean.addInitParameter("loginPassword", statViewServletLoginPassword);
        // 是否能够重置数据
        servletRegistrationBean.addInitParameter("resetEnable", "true");
        return servletRegistrationBean;
    }
 
    /**
     * Druid监控过滤器配置规则
     */
    @Bean
    @ConditionalOnMissingBean
    public FilterRegistrationBean<Filter> filterRegistrationBean() {
        FilterRegistrationBean<Filter> filterFilterRegistrationBean = new FilterRegistrationBean<>();
        filterFilterRegistrationBean.setFilter(new WebStatFilter());
        // 添加过滤规则
        filterFilterRegistrationBean.addUrlPatterns("/*");
        // 添加不需要忽略的格式信息
        filterFilterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterFilterRegistrationBean;
    }
}
